﻿using LevelEditor.Model.Entity;
using LevelEditor.Utils;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace LevelEditor.Model.IO
{
    public class GameSpritesIO
    {
        // Fields
        public static string SPRITE_LIST_XML = @"Assets\sprites_list.xml";

        // Methods
        public static List<GameSprite> LoadGameSprites()
        {
            Type[] knowedTypes = new Type[] { typeof(GameSprite), typeof(ActorSprite) };
            FileInfo spritesListXml = new FileInfo(FileUtil.AppStartUpPath + SPRITE_LIST_XML);
            List<GameSprite> gameSprites = new List<GameSprite>();
            if (spritesListXml.Exists)
            {
                XmlSerializer serializer = new XmlSerializer(typeof(List<GameSprite>), knowedTypes);
                using (FileStream stream = new FileStream(FileUtil.AppStartUpPath + SPRITE_LIST_XML, FileMode.Open, FileAccess.Read))
                {
                    gameSprites = serializer.Deserialize(stream) as List<GameSprite>;
                    stream.Close();
                }
            }
            return gameSprites;
        }

        public static void SaveGameSprites(List<GameSprite> gameSprite)
        {
            Type[] knowedTypes = new Type[] { typeof(GameSprite), typeof(ActorSprite) };
            XmlSerializer serializer = new XmlSerializer(gameSprite.GetType(), knowedTypes);

            DirectoryInfo assetsDir = new DirectoryInfo(FileUtil.AppStartUpPath + "Assets");
            if (!assetsDir.Exists)
                assetsDir.Create();

            using (FileStream stream = new FileStream(FileUtil.AppStartUpPath + SPRITE_LIST_XML, FileMode.Create, FileAccess.ReadWrite))
            {
                serializer.Serialize((Stream)stream, gameSprite);
                stream.Close();
            }
        }
    }
}
